import {
  AfterViewInit,
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  ElementRef,
  EventEmitter,
  Input,
  NgZone,
  OnChanges,
  OnDestroy,
  OnInit,
  SimpleChanges,
  ViewChild,
  ViewContainerRef,
  inject,
  Type
} from '@angular/core';
import { PageComponent } from '../page.component';
import { MAX_SAFE_PAGE_SIZE, PageLink, PageQueryParam, TimePageLink } from '@shared/models/page/page-link';
import { MatDialog } from '@angular/material/dialog';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort, SortDirection } from '@angular/material/sort';
import { TableDataSource } from '@shared/models/table/table-datasource';
import {
  debounceTime,
  distinctUntilChanged,
  skip,
  takeUntil,
  merge,
  forkJoin,
  Subject,
  Subscription,
  Observable,
  of,
  catchError,
  map
} from 'rxjs';
import { Direction, SortOrder } from '@shared/models/page/sort-order';
import { TranslateService, TranslatePipe } from '@ngx-translate/core';
import { BaseData } from '@shared/models/base-data';
import { ActivatedRoute, QueryParamsHandling, Router } from '@angular/router';
import {
  CellActionDescriptor,
  CellActionDescriptorType,
  ActionTableColumn,
  ChipsTableColumn,
  TableColumnDef,
  LinkTableColumn,
  TableColumn,
  BaseTableColumn,
  TableConfig,
  GroupActionDescriptor,
  HeaderActionDescriptor
} from '@shared/models/table/table-config.models';
import { DialogService } from '@core/services/dialog.service';
import { ToastService } from '@core/services/toast.service';
import { AnchorComponent } from '../anchor.component';
import { isEqual, isNotEmptyStr, isUndefined } from '@shared/utils';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import { hidePageSizePixelValue } from '@shared/models/constants';
import { ITableComponent } from '@shared/models/table/table-component.models';
import { FormBuilder, ReactiveFormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { MatTableModule } from '@angular/material/table';
import { MatPaginatorModule } from '@angular/material/paginator';
import { MatSortModule } from '@angular/material/sort';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatTooltipModule } from '@angular/material/tooltip';
import { MatSidenavModule } from '@angular/material/sidenav';
import { MatMenuModule } from '@angular/material/menu';
import { MatDividerModule } from '@angular/material/divider';
import { RouterModule } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { ItemAddDialogComponent } from './item-add-dialog.component';
import { ItemAddDialogData, ItemAction } from '@shared/models/table/table-data.models';

@Component({
  selector: 'cne-table',
  standalone: true,
  templateUrl: './table.component.html',
  styleUrls: ['./table.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [
    CommonModule,
    ReactiveFormsModule,
    FormsModule,
    RouterModule,
    MatTableModule,
    MatPaginatorModule,
    MatSortModule,
    MatCheckboxModule,
    MatButtonModule,
    MatIconModule,
    MatToolbarModule,
    MatFormFieldModule,
    MatInputModule,
    MatTooltipModule,
    MatSidenavModule,
    MatMenuModule,
    MatDividerModule,
    AnchorComponent,
    TranslatePipe
  ]
})
export class TableComponent<T extends BaseData> extends PageComponent
  implements ITableComponent<T>, AfterViewInit, OnInit, OnChanges, OnDestroy
{
  // ========== 输入配置 ==========
  @Input() tableConfig: TableConfig<T>; // 表格配置对象

  // ========== 依赖注入 ==========
  public route = inject(ActivatedRoute); // 路由参数服务
  protected translate = inject(TranslateService); // 国际化翻译服务
  protected dialog = inject(MatDialog); // Material 对话框服务
  protected dialogService = inject(DialogService); // 自定义对话框服务
  protected toastService = inject(ToastService); // Toast 通知服务
  protected domSanitizer = inject(DomSanitizer); // DOM 安全处理服务
  protected cd = inject(ChangeDetectorRef); // 变更检测引用
  protected router = inject(Router); // 路由服务
  protected elementRef = inject(ElementRef); // 组件宿主元素的引用，用于访问组件的 DOM 元素（如获取宽度、尺寸观察等）
  protected fb = inject(FormBuilder); // 表单构建器
  protected zone = inject(NgZone); // Angular 区域服务

  // ========== 操作描述符 ==========
  headerActionDescriptors: Array<HeaderActionDescriptor> = []; // 表头操作描述符数组
  groupActionDescriptors: Array<GroupActionDescriptor<T>> = []; // 批量操作描述符数组
  cellActionDescriptors: Array<CellActionDescriptor<T>> = []; // 单元格操作描述符数组

  // ========== 列定义 ==========
  actionColumns: Array<ActionTableColumn<T>> = []; // 操作列数组
  dataColumns: Array<TableColumn<T>> = []; // 数据列数组
  displayedColumns: string[] = []; // 显示的列键名数组

  // ========== 缓存 ==========
  headerCellStyleCache: Array<Record<string, unknown>> = []; // 表头单元格样式缓存
  cellContentCache: Array<SafeHtml> = []; // 单元格内容缓存（安全 HTML）
  cellTooltipCache: Array<string> = []; // 单元格提示信息缓存
  cellStyleCache: Array<Record<string, unknown>> = []; // 单元格样式缓存

  // ========== 状态控制 ==========
  selectionEnabled = false; // 是否启用行选择功能
  defaultPageSize = 10; // 默认每页显示数量
  displayPagination = true; // 是否显示分页器
  hidePageSize = false; // 是否隐藏页面大小选择（接口外的额外属性）
  pageSizeOptions: number[] = []; // 页面大小选项数组
  pageLink!: PageLink; // 分页链接对象
  pageMode = true; // 是否为分页模式
  textSearchMode = false; // 是否为文本搜索模式
  timewindow: unknown | null = null; // 时间窗口对象
  dataSource: TableDataSource<T>; // 表格数据源（接口中为 unknown，实现为 TableDataSource<T> | null）
  isDetailsOpen = false; // 详情面板是否打开
  detailsPanelOpened = new EventEmitter<boolean>(); // 详情面板打开状态事件发射器

  // ========== 视图引用（实现接口） ==========
  @ViewChild('tableHeader', { static: true }) tableHeaderAnchor!: AnchorComponent; // 表格头部锚点组件引用（接口中为 unknown，实际为 AnchorComponent）
  @ViewChild('searchInput') searchInputField!: ElementRef; // 搜索输入框元素引用
  @ViewChild(MatPaginator) paginator: MatPaginator; // 分页器组件引用
  @ViewChild(MatSort) sort!: MatSort; // 排序组件引用
  public viewContainerRef = inject(ViewContainerRef); // 视图容器引用（用于动态加载组件）

  // ========== 表单控制 ==========
  textSearch = this.fb.control('', { nonNullable: true }); // 文本搜索表单控件

  // ========== 私有状态 ==========
  private updateDataSubscription: Subscription; // 数据更新订阅对象
  private viewInited = false; // 视图是否已初始化标志
  private widgetResize$: ResizeObserver; // 组件尺寸变化观察器
  private destroy$ = new Subject<void>(); // 组件销毁信号（用于取消订阅）

  // ========== 额外属性（接口外） ==========
  cellActionType = CellActionDescriptorType; // 单元格操作类型枚举（用于模板）

  ngOnInit(): void {
    // 初始化：从 Input 或路由数据获取配置
    if (this.tableConfig) {
      this.init(this.tableConfig);
    } else {
      this.route.data.pipe(takeUntil(this.destroy$)).subscribe((data) => {
        const config = data['tableConfig'];
        if (config) {
          this.init(config);
        }
      });
    }
    // 监听组件尺寸变化，自动隐藏/显示页面大小选择器
    this.widgetResize$ = new ResizeObserver(() => {
      this.zone.run(() => {
        // 判断是否需要隐藏页面大小选择器（屏幕宽度 < 550px 时隐藏）
        const showHidePageSize = this.elementRef.nativeElement.offsetWidth < hidePageSizePixelValue;
        if (showHidePageSize !== this.hidePageSize) {
          this.hidePageSize = showHidePageSize;
          this.cd.markForCheck(); // 触发变更检测更新 UI
        }
      });
    });
    this.widgetResize$.observe(this.elementRef.nativeElement); // 开始监听组件尺寸变化
  }

  override ngOnDestroy(): void {
    if (this.widgetResize$) {
      this.widgetResize$.disconnect(); // 停止监听组件尺寸变化
    }
    if (this.updateDataSubscription) {
      this.updateDataSubscription.unsubscribe(); // 取消数据更新订阅
    }
    this.destroy$.next(); // 发送销毁信号
    this.destroy$.complete(); // 完成销毁信号流
  }

  ngOnChanges(changes: SimpleChanges): void {
    for (const propName of Object.keys(changes)) {
      const change = changes[propName];
      if (!change.firstChange && change.currentValue !== change.previousValue) {
        if (propName === 'tableConfig' && change.currentValue) {
          // 重新初始化表格配置：当配置变化时，需要更新列定义、操作描述符、数据源等
          // 例如：切换不同表格、列配置变化、数据源变化等场景
          this.init(change.currentValue);
        }
      }
    }
  }

  /**
   * 核心初始化方法：配置表格的所有组件和状态
   * 1. 动态加载头部组件（如有）
   * 2. 初始化操作描述符（含删除操作）
   * 3. 从路由参数恢复分页/排序/搜索状态
   * 4. 创建数据源并加载初始数据
   */
  private init(tableConfig: TableConfig<T>): void {
    this.isDetailsOpen = false;
    this.tableConfig = tableConfig;
    this.pageMode = this.tableConfig.pageMode;
    if (this.tableConfig.headerComponent) { // 动态加载自定义头部组件
      const viewContainerRef = this.tableHeaderAnchor.viewContainerRef; // 获取视图容器引用
      viewContainerRef.clear(); // 清空视图容器
      const componentRef = viewContainerRef.createComponent(this.tableConfig.headerComponent); // 创建组件实例
      const headerComponent = componentRef.instance;
      headerComponent.tableConfig = this.tableConfig;
    }

    // 建立配置与组件实例的双向引用
    this.tableConfig.setTable(this);
    // this.translations = this.tableConfig.itemTranslations; // 国际化翻译
    
    // 复制操作描述符（避免直接修改配置）
    this.headerActionDescriptors = [...this.tableConfig.headerActionDescriptors];
    this.groupActionDescriptors = [...this.tableConfig.groupActionDescriptors];
    this.cellActionDescriptors = [...this.tableConfig.cellActionDescriptors];

    // 如果启用删除功能，自动添加删除操作描述符
    if (this.tableConfig.itemsDeleteEnabled) {
      this.cellActionDescriptors.push({
        name: this.translate.instant('action.delete'),
        icon: 'delete',
        isEnabled: (item) => this.tableConfig.deleteEnabled(item),
        onAction: ($event, item) => this.deleteItem($event, item)
      });
      this.groupActionDescriptors.push({
        name: this.translate.instant('action.delete'),
        icon: 'delete',
        isEnabled: true,
        onAction: ($event, items) => this.deleteItems($event, items)
      });
    }

    // 根据是否有可用的批量操作决定是否启用选择功能
    const enabledGroupActionDescriptors = this.groupActionDescriptors.filter((descriptor) => descriptor.isEnabled);
    this.selectionEnabled = this.tableConfig.selectionEnabled && enabledGroupActionDescriptors.length > 0;

    // 更新列配置
    this.columnsUpdated();

    // 从路由查询参数恢复状态（分页、排序、搜索）
    const routerQueryParams: PageQueryParam = this.route.snapshot.queryParams;
    this.displayPagination = this.tableConfig.displayPagination;
    this.defaultPageSize = this.tableConfig.defaultPageSize;
    this.pageSizeOptions = [this.defaultPageSize, this.defaultPageSize * 2, this.defaultPageSize * 3];

    // 初始化 PageLink：优先使用路由参数，其次使用默认配置
    let sortOrder: SortOrder | null = null;
    let initialAction: string | undefined; // 初始动作
    if (this.pageMode) {
      initialAction = routerQueryParams?.action;
      if (
        this.tableConfig.defaultSortOrder ||
        routerQueryParams.hasOwnProperty('direction') ||
        routerQueryParams.hasOwnProperty('property')
      ) {
        sortOrder = {
          property: (routerQueryParams?.property) || this.tableConfig.defaultSortOrder.property,
          direction: (routerQueryParams?.direction) || this.tableConfig.defaultSortOrder.direction
        };
      }
    } else if (this.tableConfig.defaultSortOrder) {
      sortOrder = {
        property: this.tableConfig.defaultSortOrder.property,
        direction: this.tableConfig.defaultSortOrder.direction
      };
    }

    // 创建分页链接对象
    if (this.tableConfig.useTimePageLink) {
      this.timewindow = this.tableConfig.defaultTimewindowInterval;
      this.pageLink = new TimePageLink(10, 0, null, sortOrder, null, null);
    } else {
      this.pageLink = new PageLink(10, 0, null, sortOrder);
    }
    this.pageLink.pageSize = this.displayPagination ? this.defaultPageSize : MAX_SAFE_PAGE_SIZE;
    
    // 从路由参数恢复分页和搜索状态
    if (this.pageMode) {
      if (routerQueryParams.hasOwnProperty('page')) {
        this.pageLink.page = Number(routerQueryParams.page);
      }
      if (routerQueryParams.hasOwnProperty('pageSize')) {
        this.pageLink.pageSize = Number(routerQueryParams.pageSize);
      }
      const textSearchParam = routerQueryParams.textSearch;
      if (isNotEmptyStr(textSearchParam)) {
        const decodedTextSearch = decodeURI(textSearchParam);
        this.textSearchMode = true;
        this.pageLink.textSearch = decodedTextSearch.trim();
        this.textSearch.setValue(decodedTextSearch, { emitEvent: false });
      }
    }
    
    // 创建数据源
    this.dataSource = this.tableConfig.dataSource(this.dataLoaded.bind(this));
    
    // 执行加载前的回调
    if (this.tableConfig.onLoadAction) {
      this.tableConfig.onLoadAction(this.route);
    }
    
    // 加载初始数据
    if (this.tableConfig.loadDataOnInit) {
      this.dataSource.loadItems(this.pageLink);
    }
    
    // 如果视图已初始化，更新分页订阅
    if (this.viewInited) {
      setTimeout(() => {
        this.updatePaginationSubscriptions();
      }, 0);
    }
    
    // 处理初始动作：从 URL 参数读取 action，执行后清空 URL 参数
    if (this.pageMode) {
      if (initialAction) {
        // 清空 URL 中的 action 参数，避免刷新时重复执行
        const queryParams: PageQueryParam = {};
        this.router.navigate([], {
          relativeTo: this.route,
          queryParams,
          queryParamsHandling: '',
          replaceUrl: true
        });
      }

      // 如果 action 是 'add'，自动触发添加操作
      if (initialAction === 'add') {
        setTimeout(() => {
          this.addItem(null);
        }, 0);
      }
    }
    
    // 关键修复：OnPush 策略下需要手动触发变更检测
    this.cd.markForCheck();
  }

  ngAfterViewInit(): void {
    // 监听搜索输入变化：防抖 150ms，避免频繁请求
    this.textSearch.valueChanges.pipe(
        debounceTime(150),
        distinctUntilChanged((prev, current) => (this.pageLink.textSearch ?? '') === current.trim()),
        takeUntil(this.destroy$)
      ).subscribe((value) => {
        if (this.pageMode) {
          // 分页模式：更新路由参数并同步数据
          const queryParams: PageQueryParam = {
            textSearch: isNotEmptyStr(value) ? encodeURI(value) : null,
            page: null
          };
          this.updatedRouterParamsAndData(queryParams as Record<string, unknown>);
        } else {
          // 非分页模式：直接更新搜索条件并刷新数据
          this.pageLink.textSearch = isNotEmptyStr(value) ? value.trim() : null;
          if (this.displayPagination) {
            this.paginator.pageIndex = 0;
          }
          this.updateData();
        }
      });

    // 设置路由查询参数同步：监听 URL 参数变化，同步到表格状态
    if (this.pageMode) {
      this.route.queryParams.pipe(
          skip(1), // 跳过首次值（已在 init 中处理）
          takeUntil(this.destroy$) // 组件销毁时取消订阅
        ).subscribe((params: PageQueryParam) => {
          if (this.displayPagination) {
            this.paginator.pageIndex = Number(params.page) || 0;
            this.paginator.pageSize = Number(params.pageSize) || this.defaultPageSize;
          }
          this.sort.active = params.property || this.tableConfig.defaultSortOrder.property;
          this.sort.direction = (params.direction || this.tableConfig.defaultSortOrder.direction).toLowerCase() as SortDirection;
          const textSearchParam = params.textSearch;
          if (isNotEmptyStr(textSearchParam)) {
            const decodedTextSearch = decodeURI(textSearchParam);
            this.textSearchMode = true;
            this.pageLink.textSearch = decodedTextSearch.trim();
            this.textSearch.setValue(decodedTextSearch, {emitEvent: false});
          } else {
            this.pageLink.textSearch = null;
            this.textSearch.reset('', {emitEvent: false});
          }
          this.updateData(); // 更新表格数据
        });
    }
    this.updatePaginationSubscriptions(); // 更新分页和排序订阅
    this.viewInited = true; // 标记视图已初始化
  }

  /**
   * 更新分页和排序订阅：合并排序变化和分页变化事件，统一更新路由参数
   */
  private updatePaginationSubscriptions(): void {
    if (this.updateDataSubscription) {
      this.updateDataSubscription.unsubscribe();
      this.updateDataSubscription = null;
    }
    
    // 监听排序变化：转换为路由查询参数（如果使用默认排序则设为 undefined）
    let paginatorSubscription$: Observable<unknown>;
    const sortSubscription$: Observable<PageQueryParam> = this.sort.sortChange.asObservable().pipe(
      map((data) => {
        const direction = data.direction.toUpperCase();
        const queryParams: PageQueryParam = {
          direction: (this.tableConfig?.defaultSortOrder?.direction === direction ? undefined : direction) as Direction,
          property: this.tableConfig?.defaultSortOrder?.property === data.active ? undefined : data.active as string
        };
        if (this.displayPagination) {
          queryParams.page = undefined;
          this.paginator.pageIndex = 0;
        }
        return queryParams;
      })
    );
    
    // 合并排序和分页订阅（如果有分页器）
    let combinedSubscription$: Observable<PageQueryParam>;
    if (this.displayPagination) {
      paginatorSubscription$ = this.paginator.page.asObservable().pipe(
        map((data) => ({
          page: data.pageIndex === 0 ? undefined : data.pageIndex, // 第一页不显示在 URL
          pageSize: data.pageSize === this.defaultPageSize ? undefined : data.pageSize // 默认页大小不显示在 URL
        }))
      );
      combinedSubscription$ = merge(sortSubscription$, paginatorSubscription$) as Observable<PageQueryParam>;
    } else {
      combinedSubscription$ = sortSubscription$;
    }
    
    // 订阅合并后的流，更新路由参数并刷新数据
    this.updateDataSubscription = combinedSubscription$
      .pipe(takeUntil(this.destroy$))
      .subscribe((queryParams) => 
        this.updatedRouterParamsAndData(queryParams as Record<string, unknown>));
  }

  addEnabled(): boolean {
    return this.tableConfig.addEnabled;
  }

  clearSelection(): void {
    this.dataSource.selection.clear();
    this.cd.detectChanges();
  }

  /**
   * 更新数据：同步当前分页/排序状态到 PageLink，然后重新加载数据
   */
  updateData(closeDetails: boolean = true, reloadItem: boolean = true): void {
    if (closeDetails) {
      this.isDetailsOpen = false;
    }
    
    // 同步分页状态
    if (this.displayPagination) {
      this.pageLink.page = this.paginator.pageIndex;
      this.pageLink.pageSize = this.paginator.pageSize;
    } else {
      this.pageLink.page = 0;
    }
    
    // 同步排序状态
    if (this.sort.active) {
      this.pageLink.sortOrder = {
        property: this.sort.active,
        direction: Direction[this.sort.direction.toUpperCase()]
      };
    } else {
      this.pageLink.sortOrder = null;
    }
    
    // 时间分页逻辑（如需要可在此扩展）
    if (this.tableConfig.useTimePageLink) {
      // TODO: 时间分页逻辑
      // const timePageLink = this.pageLink as TimePageLink;
      // const interval = getTimePageLinkInterval(this.timewindow);
      // timePageLink.startTime = interval.startTime;
      // timePageLink.endTime = interval.endTime;
    }
    
    // 重新加载数据
    this.dataSource.loadItems(this.pageLink);

    // TODO: 重新加载详情面板
    // if (reloadItem && this.isDetailsOpen && this.detailsPanel) {
    //   this.detailsPanel.reloadItem();
    // }
  }

  private dataLoaded(col?: number, row?: number): void {
    if (isFinite(col as number) && isFinite(row as number)) {
      this.clearCellCache(col as number, row as number);
    } else {
      this.headerCellStyleCache.length = 0;
      this.cellContentCache.length = 0;
      this.cellTooltipCache.length = 0;
      this.cellStyleCache.length = 0;
    }
    // 关键修复：数据加载完成后触发变更检测（OnPush 策略需要）
    this.cd.markForCheck();
  }

  onRowClick($event: Event, item: T): void {
    if (!this.tableConfig.handleRowClick($event, item)) {
      this.toggleDetails($event, item);
    }
  }

  toggleDetails($event: Event, item: T): void {
    if ($event) {
      $event.stopPropagation();
    }
    if (this.dataSource.toggleCurrentItem(item)) {
      this.isDetailsOpen = true;
    } else {
      this.isDetailsOpen = !this.isDetailsOpen;
    }
    this.detailsPanelOpened.emit(this.isDetailsOpen);
  }

  addItem($event: Event): void {
    let item$: Observable<T>;
    if (this.tableConfig.addItem) {
      // 如果提供了 addItem 函数，直接调用
      item$ = this.tableConfig.addItem();
    } else {
      // 如果提供了对话框组件，打开对话框
      item$ = this.dialog.open<ItemAddDialogComponent, ItemAddDialogData<T>, T>(ItemAddDialogComponent, {
        disableClose: true,
        panelClass: ['cne-dialog', 'cne-fullscreen-dialog'],
        data: {
          tableConfig: this.tableConfig
        }
      }).afterClosed();
    }
    
    item$.pipe(
        takeUntil(this.destroy$)
      ).subscribe((item) => {
        if (item) {
          this.updateData();
          this.tableConfig.itemAdded(item);
        }
      });
  }

  onItemUpdated(item: T): void {
    this.updateData(false, false);
    this.tableConfig.itemUpdated(item);
  }

  onItemAction(action: ItemAction<T>): void {
    if (action.action === 'delete') {
      this.deleteItem(action.event, action.item);
    }
  }

  deleteItem($event: Event, item: T): void {
    if ($event) {
      $event.stopPropagation();
    }
    this.dialogService.confirm(
        this.tableConfig.deleteItemTitle(item),
        this.tableConfig.deleteItemContent(item),
        this.translate.instant('action.no'),
        this.translate.instant('action.yes'),
        false
      )
      .pipe(takeUntil(this.destroy$))
      .subscribe((result) => {
        if (result) {
          this.tableConfig.deleteItem(item.id)
            .pipe(
              takeUntil(this.destroy$)
            )
            .subscribe(() => {
              this.updateData();
              this.tableConfig.itemsDeleted([item.id]);
            });
        }
      });
  }

  deleteItems($event: Event, items: T[]): void {
    if ($event) {
      $event.stopPropagation();
    }
    this.dialogService.confirm(
        this.tableConfig.deleteItemsTitle(items.length),
        this.tableConfig.deleteItemsContent(items.length),
        this.translate.instant('action.no'),
        this.translate.instant('action.yes'),
        false
      )
      .pipe(takeUntil(this.destroy$))
      .subscribe((result) => {
        if (result) {
          const tasks: Observable<string>[] = [];
          items.forEach((item) => {
            if (this.tableConfig.deleteEnabled(item)) {
              tasks.push(this.tableConfig.deleteItem(item.id).pipe(
                  map(() => item.id),
                  catchError(() => of(null))
                )
              );
            }
          });
          forkJoin(tasks)
            .pipe(takeUntil(this.destroy$))
            .subscribe((ids) => {
              this.updateData();
              this.tableConfig.itemsDeleted(ids.filter(id => id !== null));
            });
        }
      });
  }

  onTimewindowChange(): void {
    if (this.displayPagination) {
      this.paginator.pageIndex = 0;
    }
    this.updateData();
  }

  enterFilterMode(): void {
    this.textSearchMode = true;
    setTimeout(() => {
      this.searchInputField.nativeElement.focus();
      this.searchInputField.nativeElement.setSelectionRange(0, 0);
    }, 10);
  }

  exitFilterMode(): void {
    this.textSearchMode = false;
    this.textSearch.reset();
  }

  resetSortAndFilter(update: boolean = true, preserveTimewindow: boolean = false): void {
    this.textSearchMode = false;
    this.pageLink.textSearch = null;
    this.textSearch.reset('', { emitEvent: false });
    if (this.tableConfig.useTimePageLink && !preserveTimewindow) {
      this.timewindow = this.tableConfig.defaultTimewindowInterval;
    }
    if (this.displayPagination) {
      this.paginator.pageIndex = 0;
    }
    const sortable = this.sort.sortables.get(this.tableConfig.defaultSortOrder.property);
    if (sortable) {
      this.sort.active = sortable.id;
      this.sort.direction = this.tableConfig.defaultSortOrder.direction === Direction.ASC ? 'asc' : 'desc';
    }
    if (update) {
      this.updatedRouterParamsAndData({}, '');
    }
  }

  /**
   * 列更新：重新分类列定义，更新显示列列表，清空缓存
   */
  columnsUpdated(resetData: boolean = false): void {
    // 分类列：数据列（TableColumn/LinkTableColumn/ChipsTableColumn）和操作列（ActionTableColumn）
    this.dataColumns = this.tableConfig.columns
      .filter((column) => column instanceof TableColumn || column instanceof LinkTableColumn || column instanceof ChipsTableColumn)
      .map((column) => column as TableColumn<T>);
    this.actionColumns = this.tableConfig.columns.filter((column) => column instanceof ActionTableColumn).map((column) => column as ActionTableColumn<T>);

    // 构建显示列列表：选择列 + 数据列 + 操作列
    this.displayedColumns = [];
    if (this.selectionEnabled) {
      this.displayedColumns.push('select');
    }
    this.tableConfig.columns.forEach((column) => {
      this.displayedColumns.push(column.key);
    });
    this.displayedColumns.push('actions');
    
    // 清空所有缓存
    this.headerCellStyleCache.length = 0;
    this.cellContentCache.length = 0;
    this.cellTooltipCache.length = 0;
    this.cellStyleCache.length = 0;
    
    // 可选：重置数据源
    if (resetData) {
      this.dataSource.reset();
    }
  }

  cellActionDescriptorsUpdated(): void {
    this.cellActionDescriptors = [...this.tableConfig.cellActionDescriptors];
  }

  /**
   * 获取表头单元格样式：使用缓存优化性能
   */
  headerCellStyle(column: TableColumnDef<T>): Record<string, unknown> {
    const index = this.tableConfig.columns.indexOf(column);
    let res = this.headerCellStyleCache[index];
    if (!res) {
      // 构建基础宽度样式
      const widthStyle: Record<string, unknown> = { width: column.width };
      if (column.width !== '0px') {
        widthStyle['minWidth'] = column.width;
        widthStyle['maxWidth'] = column.width;
      }
      // 如果是 TableColumn，合并自定义样式函数返回的样式
      if (column instanceof TableColumn) {
        res = { ...column.headerCellStyleFunction(column.key), ...widthStyle };
      } else {
        res = widthStyle;
      }
      this.headerCellStyleCache[index] = res; // 缓存结果
    }
    return res;
  }

  clearCellCache(col: number, row: number): void {
    const index = row * this.tableConfig.columns.length + col;
    delete this.cellContentCache[index];
    this.cellTooltipCache[index] = undefined;
    delete this.cellStyleCache[index];
  }

  /**
   * 获取单元格内容：使用缓存和 DOM 安全处理
   * 计算方式：index = row * columns.length + col
   */
  cellContent(item: T, column: TableColumnDef<T>, row: number): SafeHtml | string {
    if (column instanceof TableColumn || column instanceof LinkTableColumn) {
      const col = this.tableConfig.columns.indexOf(column);
      const index = row * this.tableConfig.columns.length + col;
      let res = this.cellContentCache[index];
      if (isUndefined(res)) {
        // 调用列的内容函数，并做安全处理（转换为 SafeHtml）
        res = this.domSanitizer.bypassSecurityTrustHtml(column.cellContentFunction(item, column.key));
        this.cellContentCache[index] = res; // 缓存结果
      }
      return res;
    } else {
      return '';
    }
  }

  cellTooltip(item: T, column: TableColumnDef<T>, row: number): string {
    if (column instanceof TableColumn || column instanceof LinkTableColumn) {
      const col = this.tableConfig.columns.indexOf(column);
      const index = row * this.tableConfig.columns.length + col;
      let res = this.cellTooltipCache[index];
      if (isUndefined(res)) {
        res = column.cellTooltipFunction(item, column.key);
        this.cellTooltipCache[index] = res;
      }
      return res;
    } else {
      return undefined;
    }
  }

  /**
   * 获取单元格样式：合并宽度样式和自定义样式函数，使用缓存优化
   */
  cellStyle(item: T, column: TableColumnDef<T>, row: number): Record<string, unknown> {
    const col = this.tableConfig.columns.indexOf(column);
    const index = row * this.tableConfig.columns.length + col;
    let res = this.cellStyleCache[index];
    if (!res) {
      // 构建基础宽度样式
      const widthStyle: Record<string, unknown> = { width: column.width };
      if (column.width !== '0px') {
        widthStyle['minWidth'] = column.width;
        widthStyle['maxWidth'] = column.width;
      }
      // 如果是 TableColumn，合并自定义样式函数返回的样式
      if (column instanceof TableColumn) {
        res = { ...column.cellStyleFunction(item, column.key), ...widthStyle };
      } else {
        res = widthStyle;
      }
      this.cellStyleCache[index] = res; // 缓存结果
    }
    return res;
  }

  trackByColumnKey(index: number, column: BaseTableColumn<T>): string {
    return column.key;
  }

  trackByItemId(index: number, item: T): string {
    return item.id || '';
  }

  protected updatedRouterParamsAndData(queryParams: Record<string, unknown>, queryParamsHandling: QueryParamsHandling = 'merge'): void {
    if (this.pageMode) {
      this.router.navigate([], {
        relativeTo: this.route,
        queryParams,
        queryParamsHandling
      });
      if (queryParamsHandling === '' && isEqual(this.route.snapshot.queryParams, queryParams)) {
        this.updateData();
      }
    } else {
      this.updateData();
    }
  }

  detectChanges(): void {
    this.cd.markForCheck();
  }
}

